package com.itlong.cloud.controller.finance;

import com.alibaba.fastjson.JSON;
import com.itlong.cloud.POJO.DTO.operate.OperateRenewManageGetDTO;
import com.itlong.cloud.POJO.DTO.property.PropertyInvoiceInfoDTO;
import com.itlong.cloud.POJO.VO.MessageVO;
import com.itlong.cloud.POJO.VO.operate.OperateBusinessOperationLogVO;
import com.itlong.cloud.POJO.VO.operate.OperateRenewManageGetVO;
import com.itlong.cloud.POJO.VO.property.PropertyInvoiceInfoVO;
import com.itlong.cloud.PlatformConstants;
import com.itlong.cloud.abstracts.BaseController;
import com.itlong.cloud.annotation.AuthAccessRequired;
import com.itlong.cloud.annotation.LoggerInfo;
import com.itlong.cloud.constants.LogDescConstant;
import com.itlong.cloud.controller.system.OperateUIManageController;
import com.itlong.cloud.enumerate.FileCatalogEnum;
import com.itlong.cloud.enumerate.OperateRenewManageOperationFunctionEnum;
import com.itlong.cloud.enumerate.ecode.BaseErrorCodeEnum;
import com.itlong.cloud.enumerate.ecode.OperateErrorCodeEnum;
import com.itlong.cloud.paymenthub.IOperateRenewManageServiceClient;
import com.itlong.cloud.thrown.DataAccessException;
import com.itlong.cloud.utils.file.UploadFileUtil;
import com.itlong.cloud.utils.network.http.HttpProtocolUtil;
import com.itlong.cloud.utils.page.Page;
import com.itlong.cloud.utils.words.NumberHandlerUtil;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.cloud.context.config.annotation.RefreshScope;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;

import javax.servlet.http.HttpServletRequest;
import java.io.InputStream;
import java.util.Map;

/**
 * <desc>
 *      运营-财务续费管理控制器
 * </desc>
 *
 * @createDate 2019/08/05
 */
@RestController
@RequestMapping("/finance/renewManage")
@RefreshScope
public class OperateRenewManageController extends BaseController {

    private  static final Logger LOG = LoggerFactory.getLogger(OperateUIManageController.class);

    @Value("${" + PlatformConstants.FILE_FTP_HOST + "}")
    public String FILE_FTP_HOST;
    @Value("${" + PlatformConstants.FILE_FTP_PORT + "}")
    public String FILE_FTP_PORT;
    @Value("${" + PlatformConstants.FILE_FTP_USERNAME + "}")
    public String FILE_FTP_USERNAME;
    @Value("${" + PlatformConstants.FILE_FTP_PASSWORD + "}")
    public String FILE_FTP_PASSWORD;
    @Value("${" + PlatformConstants.FILE_ACCESS_URL + "}")
    public String FILE_ACCESS_URL;

    @Autowired
    private IOperateRenewManageServiceClient iOperateRenewManageServiceClient;

    /**
     * <desc>
     *      分页获取财务续费信息
     * </desc>
     *
     * @param operateRenewManageGetDTO 获取财务续费信息DTO
     * @return 标准格式化响应结果
     * @author wangzhi
     * @createDate 2019/08/05
     */
    @ResponseBody
    @AuthAccessRequired
    @PostMapping("getPage")
    public Object getPage(OperateRenewManageGetDTO operateRenewManageGetDTO){
        try {
            HttpServletRequest request=((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
            operateRenewManageGetDTO= HttpProtocolUtil.parseRequestParamToDTO(OperateRenewManageGetDTO.class,request);
            if (operateRenewManageGetDTO == null) {
                return new MessageVO(BaseErrorCodeEnum.NOT_PARAM.getErrorCode());
            }
            Page<OperateRenewManageGetVO> operateRenewManageGetVOPage = iOperateRenewManageServiceClient.getPage(operateRenewManageGetDTO);
            Map<String ,Object> appendInfoMap=iOperateRenewManageServiceClient.getAppendInfo(operateRenewManageGetDTO);
            // 获取财务续费信息总金额
            String totalAmount = iOperateRenewManageServiceClient.getTotalAmount(operateRenewManageGetDTO);
            appendInfoMap.put("tolalAmount",totalAmount);
            return new MessageVO(JSON.toJSONString(appendInfoMap), BaseErrorCodeEnum.SUCCESS.getErrorCode(), operateRenewManageGetVOPage);
        } catch (Exception e) {
            throw new DataAccessException("【运营-财务续费管理getPage】分页获取财务续费信息失败",e);
        }
    }

    /**
     * <desc>
     *      获取财务续费信息详情
     * </desc>
     *
     * @param operateRenewManageGetDTO 获取财务续费信息DTO
     * @return 标准格式化响应结果
     * @author wangzhi
     * @createDate 2019/08/05
     */
    @ResponseBody
    @AuthAccessRequired
    @PostMapping("getOne")
    public Object getOne(OperateRenewManageGetDTO operateRenewManageGetDTO){
        try {
            HttpServletRequest request=((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
            operateRenewManageGetDTO= HttpProtocolUtil.parseRequestParamToDTO(OperateRenewManageGetDTO.class,request);
            if (operateRenewManageGetDTO == null) {
                return new MessageVO(BaseErrorCodeEnum.NOT_PARAM.getErrorCode());
            }
            if (StringUtils.isBlank(operateRenewManageGetDTO.getOrderId())) {
                return new MessageVO(BaseErrorCodeEnum.NOT_PARAM.getErrorCode());
            }
            //LOG.info(operateRenewManageGetDTO.toString());
            OperateRenewManageGetVO operateRenewManageGetVO = iOperateRenewManageServiceClient.getOne(operateRenewManageGetDTO);
            return new MessageVO(BaseErrorCodeEnum.SUCCESS.getErrorCode(), operateRenewManageGetVO);
        } catch (Exception e) {
            throw new DataAccessException("【运营-财务续费管理getOne】获取财务续费信息详情失败",e);
        }
    }

    /**
     * <desc>
     *      财务续费收款确认
     * </desc>
     *
     * @param operateRenewManageGetDTO 财务续费收款确认DTO
     * @return 标准格式化响应结果
     * @Author Zhu.yj
     * @createDate  2019/11/27
     */
    @AuthAccessRequired
    @ResponseBody
    @LoggerInfo(operateDesc = LogDescConstant.FINANCE_RENEW_MANAGE_CONFIRM_LOG_DESC)
    @PostMapping("confirm")
    public Object confirm(OperateRenewManageGetDTO operateRenewManageGetDTO){
        try {
            HttpServletRequest request = ((ServletRequestAttributes)RequestContextHolder.getRequestAttributes()).getRequest();
            operateRenewManageGetDTO = HttpProtocolUtil.parseRequestParamToDTO(OperateRenewManageGetDTO.class,request);
            if (operateRenewManageGetDTO == null ||StringUtils.isEmpty(operateRenewManageGetDTO.getOrderId()) || operateRenewManageGetDTO.getConfirmStatus() == null
                    || operateRenewManageGetDTO.getFeeStatus() == null){
                return new MessageVO(BaseErrorCodeEnum.NOT_PARAM.getErrorCode());
            }
            if (!NumberHandlerUtil.isInRange(operateRenewManageGetDTO.getConfirmStatus(),1,2)){
                return new MessageVO(BaseErrorCodeEnum.PARAM_ERR.getErrorCode());
            }
            operateRenewManageGetDTO.setIp(HttpProtocolUtil.getIpAddr(request));
            iOperateRenewManageServiceClient.confirm(operateRenewManageGetDTO);
            return new MessageVO(operateRenewManageGetDTO.getOrderId(),BaseErrorCodeEnum.SUCCESS.getErrorCode());
        }catch (Exception e){
            throw new DataAccessException("【运营—财务续费管理confirm】财务续费收款确认失败",e);
        }
    }

    /**
     * <desc>
     *      财务续费审批
     * </desc>
     *
     * @param operateRenewManageGetDTO 财务续费审批DTO
     * @return 标准格式化响应结果
     * @author wangzhi
     * @createDate 2019/08/05
     */
    @AuthAccessRequired
    @LoggerInfo(operateDesc = LogDescConstant.FINANCE_RENEW_MANAGE_ACCEPT_LOG_DESC)
    @ResponseBody
    @PostMapping("accept")
    public Object accept(OperateRenewManageGetDTO operateRenewManageGetDTO){
        try {
            HttpServletRequest request=((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
            operateRenewManageGetDTO= HttpProtocolUtil.parseRequestParamToDTO(OperateRenewManageGetDTO.class,request);
            if (operateRenewManageGetDTO == null || StringUtils.isEmpty(operateRenewManageGetDTO.getOrderIds()) ||operateRenewManageGetDTO.getType() == null) {
                return new MessageVO(BaseErrorCodeEnum.NOT_PARAM.getErrorCode());
            }
            if(!NumberHandlerUtil.isInRange(operateRenewManageGetDTO.getType(),1,5)){
                return new MessageVO(BaseErrorCodeEnum.PARAM_ERR.getErrorCode());
            }
            if((operateRenewManageGetDTO.getType() == OperateRenewManageOperationFunctionEnum.FUNCTION_ABANDON.getType()
                || operateRenewManageGetDTO.getType() == OperateRenewManageOperationFunctionEnum.FUNCTION_UNDO.getType()) && StringUtils.isEmpty(operateRenewManageGetDTO.getRemark())){
                return new MessageVO(BaseErrorCodeEnum.NOT_PARAM.getErrorCode());
            }
            operateRenewManageGetDTO.setIp(HttpProtocolUtil.getIpAddr(request));
            iOperateRenewManageServiceClient.accept(operateRenewManageGetDTO);
            return new MessageVO(BaseErrorCodeEnum.SUCCESS.getErrorCode());
        } catch (Exception e) {
            throw new DataAccessException("【运营-财务续费管理accept】财务续费审批失败",e);
        }
    }
    
    /**
     * <desc>
     *      上传发票
     * </desc>
     *
     * @param
     * @return
     * @Author Zhu.yj
     * @createDate  2019/11/22
     */
    @ResponseBody
    @PostMapping("upload")
    public Object upload(MultipartFile fileData,HttpServletRequest request){
        MessageVO messageVO;
        String fileUrl = ""; //返回文件链接地址
        String fileType ="";  //文件类型
        String fileExt = "pdf|jpg|png|jpeg|PDF|JPG|PNG|JPEG";
        try {
            MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
            fileData = multipartRequest.getFile("fileData");
            //判断资源是否为空
            if(fileData==null){
                return new MessageVO(OperateErrorCodeEnum.IMAGE_RESOURCE_EMPTY_ERR.getErrorCode());
            }
            //判断文件大小是否超出限制
            if (fileData.getSize() > 100 * 1024 *1024){
                return new MessageVO(OperateErrorCodeEnum.FILE_SIZE_OUT_OF_LIMIT_ERR.getErrorCode());
            }
            String fileName = fileData.getOriginalFilename();
            if(StringUtils.isBlank(fileName)){
                return new MessageVO(OperateErrorCodeEnum.IMAGE_RESOURCE_EMPTY_ERR.getErrorCode());
            }
            fileType = fileName.substring(fileName.lastIndexOf("."));
            //判断文件类型
            if(StringUtils.isBlank(fileType)||fileExt.contains(fileType)){
                return new MessageVO(OperateErrorCodeEnum.IMAGE_TYPE_ANVALID_ERR.getErrorCode());
            }
            fileUrl = uploadBill(fileData.getInputStream(),fileType, FileCatalogEnum.OPERATE_CLOUD_SERVE_COST_BILL_FILE.getType());
            //LOG.info("文件路径为:"+fileUrl);
            if (StringUtils.isBlank(fileUrl)) {
                return new MessageVO(BaseErrorCodeEnum.ERROR.getErrorCode());
            }
            return new MessageVO(BaseErrorCodeEnum.SUCCESS.getErrorCode(),(Object) fileUrl);
        }catch (Exception e) {
            throw new DataAccessException("【运营财务续费管理upload】上传发票失败", e);
        }
    }

    /**
     * <desc>
     *      分页获取业务日志
     * </desc>
     *
     * @param operateRenewManageGetDTO 查询参数
     * @return 业务日志分页信息
     * @Author Zhu.yj
     * @createDate  2019/11/27
     */
    @ResponseBody
    @PostMapping("getLogPage")
    public Object getLogPage(OperateRenewManageGetDTO operateRenewManageGetDTO){
        try{
            HttpServletRequest request = ((ServletRequestAttributes)RequestContextHolder.getRequestAttributes()).getRequest();
            operateRenewManageGetDTO = HttpProtocolUtil.parseRequestParamToDTO(OperateRenewManageGetDTO.class,request);
            if (operateRenewManageGetDTO == null || StringUtils.isEmpty(operateRenewManageGetDTO.getOrderId())){
                return new MessageVO(BaseErrorCodeEnum.NOT_PARAM.getErrorCode());
            }
            Page<OperateBusinessOperationLogVO> operateBusinessOperationLogVOPage =iOperateRenewManageServiceClient.getLogPage(operateRenewManageGetDTO);
            return new MessageVO(BaseErrorCodeEnum.SUCCESS.getErrorCode(),operateBusinessOperationLogVOPage);
        }catch (Exception e){
            throw new DataAccessException("【运营财务续费管理getLogPage】,获取财务续费订单业务日志失败",e);
        }
    }

    /**
     * <desc>
     *      获取开票信息
     * </desc>
     *
     * @param operateRenewManageGetDTO 发票信息DTO
     * @return
     * @Author Zhu.yj
     * @createDate  2019/11/22
     */
    @ResponseBody
    @AuthAccessRequired
    @PostMapping("getBillInfo")
    public Object getBillInfo(OperateRenewManageGetDTO operateRenewManageGetDTO){
        try{
            HttpServletRequest request = ((ServletRequestAttributes)RequestContextHolder.getRequestAttributes()).getRequest();
            operateRenewManageGetDTO = HttpProtocolUtil.parseRequestParamToDTO(OperateRenewManageGetDTO.class,request);
            if(operateRenewManageGetDTO==null || operateRenewManageGetDTO.getOrderId() == null){
                return new MessageVO(BaseErrorCodeEnum.NOT_PARAM.getErrorCode());
            }
            PropertyInvoiceInfoVO propertyInvoiceInfoVO = iOperateRenewManageServiceClient.getBillInfo(operateRenewManageGetDTO);
            return new MessageVO(BaseErrorCodeEnum.SUCCESS.getErrorCode(),propertyInvoiceInfoVO);
        }catch (Exception e){
            throw new DataAccessException("【运营_财务续费管理getBillInfo】获取发票信息失败",e);
        }
    }

    /**
     * <desc>
     *      开票
     * </desc>
     *
     * @param propertyInvoiceInfoDTO 待开发票信息DTO
     * @return
     * @Author Zhu.yj
     * @createDate  2019/11/25
     */
    @ResponseBody
    @LoggerInfo(operateDesc = LogDescConstant.FINANCE_RENEW_MANAGE_BILLING_LOG_DESC)
    @PostMapping("billing")
    public Object billing(PropertyInvoiceInfoDTO propertyInvoiceInfoDTO){
        try {
            HttpServletRequest request =((ServletRequestAttributes)RequestContextHolder.getRequestAttributes()).getRequest();
            propertyInvoiceInfoDTO = HttpProtocolUtil.parseRequestParamToDTO(PropertyInvoiceInfoDTO.class,request);
            if(propertyInvoiceInfoDTO==null || StringUtils.isEmpty(propertyInvoiceInfoDTO.getOrderId())|| StringUtils.isEmpty(propertyInvoiceInfoDTO.getInvoiceNumber())){
                return new MessageVO(BaseErrorCodeEnum.NOT_PARAM.getErrorCode());
            }
            propertyInvoiceInfoDTO.setIp(HttpProtocolUtil.getIpAddr(request));
            iOperateRenewManageServiceClient.billing(propertyInvoiceInfoDTO);
            return new MessageVO(propertyInvoiceInfoDTO.getOrderId(),BaseErrorCodeEnum.SUCCESS.getErrorCode());
        }catch (Exception e){
            throw new DataAccessException("【运营_财务续费管理billing】开票失败",e);
        }
    }


    /**
     * <desc>
     *      上传文件
     * </desc>
     *
     * @param stream
     * @param fileType
     * @param fileCatalog
     * @return
     * @Author Zhu.yj
     * @createDate  2019/11/22
     */
    private String uploadBill(InputStream stream, String fileType, String fileCatalog) throws Exception{
        String fileUrl="";
        //上传到ftp服务器
        UploadFileUtil.UploadFile uploadFileUtil = new UploadFileUtil().new UploadFile(
                FILE_FTP_HOST,
                FILE_FTP_USERNAME,
                FILE_FTP_PASSWORD,
                FILE_FTP_PORT,
                stream,
                fileType,
                FILE_ACCESS_URL,
                fileCatalog
        );
        Map<String, Object> resultMap = UploadFileUtil.uploadFile(uploadFileUtil);
        Boolean returnCode = (Boolean) resultMap.get("returnCode");
        if (!returnCode) {
            return fileUrl;
        }
        fileUrl = resultMap.get("accessPath").toString();
        return fileUrl;
    }
}
